import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/pv_inverter_detail/pv_inverter_detail_model.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/styles/styles.dart';
import 'yt_column_model.dart';

abstract class YtProfileTableData {
  Map<String, dynamic> toJson();
}

class YtProfileTable<T extends YtProfileTableData> extends StatefulWidget {
  final List<T> dataSource;

  final List<YtColumnModel<T>> columns;

  /// 展示的行数
  final int? rowsCount;

  final double? tableWidth;

  /// 单元格的高度
  final double cellHeight;

  /// 是否开启展开收缩功能
  final bool isExpand;

  final Color backgroundColor;

  const YtProfileTable(
      {super.key,
      this.tableWidth,
      this.rowsCount,
      this.cellHeight = 50,
      this.isExpand = false,
      this.backgroundColor = Colour.white,
      required this.dataSource,
      required this.columns});

  @override
  State<YtProfileTable<T>> createState() => _YtProfileTableState<T>();
}

class _YtProfileTableState<T extends YtProfileTableData>
    extends State<YtProfileTable<T>> {
  bool isMore = false;

  double screenWidth = 375.w;

  List<double> cellWidthList = [];

  @override
  void initState() {
    screenWidth = ScreenUtil().screenWidth;
    cellWidthList = calcCellsWidth();
    super.initState();
  }

  int get showRolNum {
    if (!isMore) {
      return widget.rowsCount ?? widget.dataSource.length;
    } else {
      return widget.dataSource.length;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Container(
          height: showRolNum * widget.cellHeight + 50,
          width: screenWidth,
          decoration: BoxDecoration(
            color: widget.backgroundColor,
            // color: Colors.green,
          ),
          child: _getTable(),
        ),
        Container(
          height: 0.5,
          color: Colour.dividerColor,
        ),
        if (widget.isExpand == true &&
            (widget.dataSource.length > (widget.rowsCount ?? 0)))
          _expandMore()
      ],
    );
  }

  List<double> calcCellsWidth() {
    if (widget.tableWidth != null) {
      screenWidth = widget.tableWidth!;
    }
    double defineWidths = 0;
    int i = 0, j = 0;
    int len = widget.columns.length;
    for (i = 0; i < len; i++) {
      double? w = widget.columns[i].width;
      if (w != null) {
        j++;
        defineWidths = defineWidths + w;
      }
    }
    if (defineWidths > screenWidth ||
        (j > len && defineWidths >= screenWidth)) {
      Log.e('总宽度大于表格宽度');
      var w = calcFixCellWidth();
      return List.generate(len, (index) => w);
    } else {
      double fixWidth = (screenWidth - defineWidths) / (len - j);
      List<double> widths = List.generate(len, (index) => fixWidth);
      for (i = 0; i < len; i++) {
        double? w = widget.columns[i].width;
        if (w != null) {
          widths[i] = w;
        }
      }
      return widths;
    }
  }

  double calcFixCellWidth() {
    return screenWidth / widget.columns.length;
  }

  ListView _getTable() {
    Log.d('dataSource==${widget.dataSource.length}');

    return ListView(
        physics: const NeverScrollableScrollPhysics(),
        padding: EdgeInsets.zero,
        children: [
          _getHeads(),
          Container(
            height: 0.5,
            color: Colour.dividerColor,
            // margin: EdgeInsets.only(left: 16.w,right: 16.w),
          ),
          _getRows()
        ]);
  }

  Row _getHeads() {
    Log.d('widget.columns==${widget.columns.length}');
    List<Container> contains = List.generate(widget.columns.length, (index) {
      double w = cellWidthList[index];
      return Container(
        alignment: Alignment.center,
        width: w,
        height: 50,
        color: Colors.white,
        child: Text(
          widget.columns[index].title,
          style: TextStyles.styleWith(14.sp, color: Colour.otherTextColor),
          textAlign: TextAlign.center,
        ),
      );
    });
    return Row(
      children: contains,
    );
  }

  Widget _getRows() {
    return SizedBox(
      height: widget.dataSource.length * 50,
      child: ListView.builder(
        physics: const NeverScrollableScrollPhysics(),
        itemCount: widget.dataSource.length,
        itemBuilder: (_, int index) => _itemWidget(index),
      ),
    );
  }

  _itemWidget(int rowIndex) {
    T rowData = widget.dataSource[rowIndex];

    List<Widget> contains = List.generate(widget.columns.length, (colIndex) {
      double w = cellWidthList[colIndex];
      YtColumnModel<T> col = widget.columns[colIndex];
      return Container(
        alignment: Alignment.center,
        width: w,
        child: col.render != null
            ? col.render!(rowData, rowIndex)
            : Text(
                rowData.toJson()[col.field]?.toString() ?? '-',
                style: TextStyles.f14,
              ),
      );
    });

    return Column(
      children: [
        Container(
          // width: 110.w,
          //   color: Colors.red,
          height: 49.5,
          alignment: Alignment.center,
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: contains,
          ),
        ),
        Container(
          height: 0.5,
          color: Colour.dividerColor,
          // margin: EdgeInsets.only(left: 16.w,right: 16.w),
        )
      ],
    );
  }

  Widget _expandMore() {
    return GestureDetector(
      onTap: () {
        setState(() {
          isMore = !isMore;
        });
      },
      child: Container(
        height: 46,
        decoration: BoxDecoration(
          color: widget.backgroundColor,
          // color: Colors.red,
          // border: const Border(
          //     top: BorderSide(color: Colour.dividerColor, width: 0.5)
          // )
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              isMore ? ResKey.retract.tr : ResKey.loadMore.tr,
              style: TextStyles.lf16,
            ),
            Icon(
              isMore
                  ? Icons.keyboard_double_arrow_up
                  : Icons.keyboard_double_arrow_down,
              color: Colour.lightTextColor,
              size: 22.w,
            )
          ],
        ),
      ),
    );
  }
}
